package com.zjs.servlet;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet(urlPatterns = {"/download"})
public class DownloadFileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取下载文件名称
        String imgName = req.getParameter("imgName");
        //在文件目录找到相应文件
        String url = "/myUploadFile/" + imgName;
        //设置编码格式
        imgName = URLEncoder.encode(imgName, "UTF-8");
        //将响应内容转换为二进制流
        resp.setContentType("application/octet-stream");
        //设置响应头，以弹窗形式展示
        resp.addHeader("Content-Disposition", "attachment;filename=" + imgName);
        req.getRequestDispatcher(url).forward(req, resp);
        //清空缓冲区
        resp.resetBuffer();
    }
}
